package com.bo.sina.weibo.share;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.bo.exception.AppException;
import com.bo.exception.WeiboException;
import com.bo.sina.send.SendPostMessage;
import com.bo.sina.send.WeiboResponse;
import com.bo.sina.weibo.access.AccessInfo;
import com.bo.sina.weibo.image.HttpImage;
import com.bo.sina.weibo.image.WeiboImage;
import com.bo.sina.weibo.login.Login;
import com.bo.weibo.bean.SendDataInfo;

public class Share {
    static Logger log = Logger.getLogger(Share.class.getName());
    public  void share(AccessInfo accessinfo,SendDataInfo senddf) throws AppException {
		
		try{
	      //session为null 必须先登录微博
        if(accessinfo.getSession()==null){
            Login login=new Login();
            WeiboResponse loginresp=login.loginWeibo(accessinfo);
            accessinfo.setSession(loginresp.getSession());
        }
        
        
        
		
		Map<String,String> paramsMap=new HashMap<String,String>();
		paramsMap.put("_surl", "");
		paramsMap.put("_t", "0");
		paramsMap.put("hottopicid", "");
		paramsMap.put("location", "home");
		paramsMap.put("module", "stissue");
		paramsMap.put("pic_id", "");
		paramsMap.put("rank", "0");
		paramsMap.put("rankid", "");
		paramsMap.put("text",senddf.getContent());
		
		
		
		if(senddf.getImageurl()!=null){
            
            WeiboImage weiboimage=new WeiboImage();
            try{
                byte[] pic=HttpImage.getUrlImg(senddf.getImageurl());
                String spic=weiboimage.upload(accessinfo, pic);
                paramsMap.put("pic_id", spic);
            }catch(AppException e){
                log.warn("NO1:"+e.getCode()+"---"+senddf.getImageurl()+"---"+senddf.getUrl());
                Thread.sleep(1000*60);
                try{
                    //第一次机会
                    if("A20001".equals(e.getCode())){
                        byte[] pic=HttpImage.getUrlImg(senddf.getImageurl());
                        String spic=weiboimage.upload(accessinfo, pic);
                        paramsMap.put("pic_id", spic);
                    }
                }catch(AppException ae){
                    log.warn("NO2:"+ae.getCode()+"---"+senddf.getImageurl()+"---"+senddf.getUrl());
                    Thread.sleep(1000*60);
                    try{
                    //第2次机会
                        if("A20001".equals(ae.getCode())){
                            byte[] pic=HttpImage.getUrlImg(senddf.getImageurl());
                            String spic=weiboimage.upload(accessinfo, pic);
                            paramsMap.put("pic_id", spic);
                        }
                    }catch(AppException ae2){
                        log.warn("NO3:"+ae.getCode()+"---"+senddf.getImageurl()+"---"+senddf.getUrl());
                        Thread.sleep(1000*60);
                        //第3次机会
                        if("A20001".equals(ae2.getCode())){
                            byte[] pic=HttpImage.getUrlImg(senddf.getImageurl());
                            String spic=weiboimage.upload(accessinfo, pic);
                            paramsMap.put("pic_id", spic);
                        }
                    }
                }
            }
        }
		
		
		
		
		
		Map<String,String> requestMap=new HashMap<String,String>();
		requestMap.put("Referer","http://www.weibo.com/minipublish?uid="+accessinfo.getUid());
		requestMap.put("Host","www.weibo.com");

		requestMap.put("Cookie",accessinfo.getSession());
		
		SendPostMessage spm=new SendPostMessage();
		WeiboResponse weibor = spm.send("http://weibo.com/aj/mblog/add?_rnd="+System.currentTimeMillis(),"UTF-8", paramsMap,requestMap);
		String entity=weibor.getMessage();

//		System.out.println(entity);
		if (entity.replace("\"", "").indexOf("code:100000") > -1) {
//			System.out.println("发布成功");
		    ShareManager.addSuccessShare(accessinfo.getNick());
		}else{
		    if(entity.indexOf("pl_login_login")!=-1){//重新登录
		        Login login=new Login();
	            WeiboResponse loginresp=login.loginWeibo(accessinfo);
	            accessinfo.setSession(loginresp.getSession());
	            log.warn(accessinfo.toString());
		    }else{
		        ShareManager.addFailShare(accessinfo.getNick());
		        throw  new AppException("512",accessinfo.toString()+"    "+entity);
		    }
			
		}
		}catch(Exception e){
		    ShareManager.addFailShare(accessinfo.getNick());
//			WeiboException.addShareExceptionNo();
			throw new AppException("512",e);
		}
	}
	
//	public  void Share(String entity,String text) {
//		HttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());
//
//
//		try {
//			HttpResponse response =null;
//			String url = entity.substring(entity
//					.indexOf("http://weibo.com/sso/login.php?"), entity
//					.indexOf("code=0")+6 );
//
//			// 获取到实际url进行连接
////			SendGetMessage sgm=new SendGetMessage();
////			WeiboResponse wbr=sgm.send(url, "utf-8");
////			System.out.println(wbr.toString());
////			entity=wbr.getMessage();
//			;
//			HttpGet getMethod = new HttpGet(url);
//			 response = client.execute(getMethod);
//			entity = EntityUtils.toString(response.getEntity());
//			System.out.println(entity);
//			for(Header h:response.getAllHeaders())
//			System.out.println(h);
//			// 获取uid
//			String uid = entity.substring(entity.indexOf("uniqueid") + 11,
//					entity.indexOf("userid") - 3);
////			String uid="1899962304";
//			System.out.println(uid);
//			
//			
//			
//			HttpPost post = new HttpPost("http://weibo.com/aj/mblog/add?_rnd="
//					+ System.currentTimeMillis());
//			post.addHeader("Referer", "http://weibo.com/u/" + uid + "");
//			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//			nvps.add(new BasicNameValuePair("_surl", ""));
//			nvps.add(new BasicNameValuePair("_t", "0"));
//			nvps.add(new BasicNameValuePair("hottopicid", ""));
//			nvps.add(new BasicNameValuePair("location", "home"));
//			nvps.add(new BasicNameValuePair("module", "stissue"));
//			nvps.add(new BasicNameValuePair("pic_id", ""));
//			nvps.add(new BasicNameValuePair("rank", "0"));
//			nvps.add(new BasicNameValuePair("rankid", ""));
//			nvps.add(new BasicNameValuePair("text", text));
//			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//			response = client.execute(post);
//
//			 entity = EntityUtils.toString(response.getEntity());
////			System.out.println(entity);
////			for(Header h:response.getAllHeaders())
////				System.out.println(h);
//			if (entity.replace("\"", "").indexOf("code:100000") > -1) {
//				System.out.println("发布成功");
//			} 
//		} catch (Exception e) {
////			e.printStackTrace();
//			try {
//				System.out.println(new String(e.getCause().getMessage().getBytes("ISO-8859-1"),"utf-8"));
//			} catch (UnsupportedEncodingException e1) {
//				e1.printStackTrace();
//			}
//		}
//
//	}
//	
//	public  void Share(String uid) {
//		HttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());
//		try {
////			String uid="1899962304";
//			System.out.println(uid);
//			
//			HttpPost post = new HttpPost("http://weibo.com/aj/mblog/add?_rnd="
//					+ System.currentTimeMillis());
//			post.addHeader("Referer", "http://weibo.com/u/" + uid + "");
//			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//			nvps.add(new BasicNameValuePair("_surl", ""));
//			nvps.add(new BasicNameValuePair("_t", "0"));
//			nvps.add(new BasicNameValuePair("hottopicid", ""));
//			nvps.add(new BasicNameValuePair("location", "home"));
//			nvps.add(new BasicNameValuePair("module", "stissue"));
////			nvps.add(new BasicNameValuePair("pic_id", pid));
//			nvps.add(new BasicNameValuePair("rank", "0"));
//			nvps.add(new BasicNameValuePair("rankid", ""));
//			nvps.add(new BasicNameValuePair("text", "haha..........."));
//			post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//			HttpResponse response = client.execute(post);
//
//			String entity = EntityUtils.toString(response.getEntity());
//			System.out.println(entity);
//			if (entity.replace("\"", "").indexOf("code:100000") > -1) {
//				System.out.println("发布成功");
//			} 
//		} catch (Exception e) {
//			e.printStackTrace();
//			
//		}
//
//	}
}
